package com.docman.controller;

import com.docman.dao.DocumentDAO;
import com.docman.domainmodel.Constants;
import com.docman.domainmodel.DocumentBean;
import com.docman.domainmodel.UserBean;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
       
	
	
	// upload settings
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
	
	
    public UploadServlet() {
        super();
    }

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setCharacterEncoding("text/html;  charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		
		DocumentBean document = new DocumentBean();		
		
		HttpSession session = request.getSession();
		//if(session.getAttribute("currentSessionUser")!= null){						
			UserBean uploader = (UserBean) session.getAttribute("currentSessionUser");
		//}
		boolean error = false; // to specify that the uploaded file is valid in terms of our constraints.Check Constants class
		// for fileTypes we support
	
		// checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(request)) {
            // if not, we stop here
            PrintWriter writer = response.getWriter();
            writer.println("Error: Form must has enctype=multipart/form-data.");
            writer.flush();
            return;
        }
 
        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // sets memory threshold - beyond which files are stored in disk 
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // sets temporary location to store files
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
 
        ServletFileUpload upload = new ServletFileUpload(factory);
         
        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);
         
        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);
        
        // constructs the directory path to store upload file
        // this path is relative to application's directory
        
        String uploadPath =Constants.filePath;
        // System.out.println(uploadPath);
        // creates the directory if it does not exist
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        
        upload.setHeaderEncoding("ISO-8858-2");
        try {
            // parses the request's content to extract file data
        	List<FileItem> formItems = upload.parseRequest(request);
        
        
			if (formItems != null && formItems.size() > 0) {
				
				// iterates over form's fields
				for (FileItem item : formItems) {
					// processes only fields that are not form fields
					
					if (!item.isFormField()) {
						
						String fileName = new File(item.getName()).getName();
						document.setDocName(fileName);
						String filePath = uploadPath + File.separator + fileName;
						document.setDocPath(filePath);
						File storeFile = new File(filePath);
						System.out.println("FİLE NAME İS:"+fileName);
						long size =item.getSize();
						System.out.println("File Size :"+size);
						String contentType = item.getContentType();
						System.out.println("Content type is (UploadServlet): "+contentType);
						System.out.println("encoding is : " + request.getCharacterEncoding());
						if(Constants.listAllowedDocumentTypes.contains(contentType)){
							// saves the file on disk
							item.write(storeFile);
							
						}
						else{
							error = true;
						}
						
					}
					
					else if(item.isFormField()){
						
						String name =item.getFieldName();
						String value=item.getString();
						System.out.println(name+value);
						if(name.equals("title")){
							
							document.setTitle(value);
							
						}
						else if(name.equals("tag")){
							
							document.setTag(value);
						}
						else if(name.equals("comment")){
							
							document.setComment(value);
						}
						
						
							document.setUploader(uploader.getUserName());
						
			            java.util.Date myDate = new java.util.Date();
						java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());
						
			            document.setUploadDate(sqlDate); 
			            //document.setRating(rating); // Rating is not assigned here
			            				
					}
						
					 
               // request.setAttribute("message","Upload has been done successfully!");
            }
				}
			          
            System.out.println("doc:"+document.toString());
       
        if(!error){
        	DocumentDAO.uploadFile(document);
        	
        }
        
        System.out.println("error is"+error);
        } catch (Exception ex) {
            request.setAttribute("message", "There was an error: " + ex.getMessage());
        }
        // redirects client to message page
        if(!error){
        	response.sendRedirect("profileServletpath");
        
        }
        else{
        	
        	response.sendRedirect("getTagServletpath?sId=0");
        }
    }

}
